package fosu.generated.service.impl;

import fosu.generated.dto.LoginDTO;
import fosu.generated.dto.RegisterDTO;
import fosu.generated.entity.User;
import fosu.generated.mapper.UserMapper;
import fosu.generated.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * 用户服务实现类
 */
@Service
public class UserServiceImpl implements UserService {

    private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

    @Autowired
    private UserMapper userMapper;

    @Override
    public User login(LoginDTO loginDTO) {
        logger.info("用户登录，用户名: {}", loginDTO.getUsername());

        User user = userMapper.findByUsername(loginDTO.getUsername());
        if (user == null) {
            logger.warn("用户名不存在: {}", loginDTO.getUsername());
            throw new RuntimeException("用户名或密码错误");
        }

        if (!user.getPassword().equals(loginDTO.getPassword())) {
            logger.warn("密码错误，用户名: {}", loginDTO.getUsername());
            throw new RuntimeException("用户名或密码错误");
        }

        logger.info("登录成功，用户ID: {}", user.getId());
        return user;
    }

    @Override
    public void register(RegisterDTO registerDTO) {
        logger.info("用户注册，用户名: {}", registerDTO.getUsername());

        // 检查用户名是否已存在
        if (userMapper.findByUsername(registerDTO.getUsername()) != null) {
            logger.warn("用户名已存在: {}", registerDTO.getUsername());
            throw new RuntimeException("用户名已存在");
        }

        // 检查手机号是否已注册
        if (userMapper.findByPhone(registerDTO.getPhone()) != null) {
            logger.warn("手机号已注册: {}", registerDTO.getPhone());
            throw new RuntimeException("手机号已注册");
        }

        // 创建用户
        User user = new User();
        user.setUsername(registerDTO.getUsername());
        user.setPassword(registerDTO.getPassword());
        user.setPhone(registerDTO.getPhone());
        user.setRealName(registerDTO.getRealName());
        user.setRole("STUDENT");
        user.setCreateTime(LocalDateTime.now());

        userMapper.insert(user);
        logger.info("注册成功，用户ID: {}", user.getId());
    }

    @Override
    public String forgotPassword(String username, String phone) {
        logger.info("找回密码，用户名: {}, 手机号: {}", username, phone);

        User user = userMapper.findByUsername(username);
        if (user == null) {
            logger.warn("用户名不存在: {}", username);
            throw new RuntimeException("用户名或手机号不匹配");
        }

        if (!user.getPhone().equals(phone)) {
            logger.warn("手机号不匹配，用户名: {}", username);
            throw new RuntimeException("用户名或手机号不匹配");
        }

        logger.info("密码找回成功，用户ID: {}", user.getId());
        return user.getPassword();
    }
}